package felix.rule.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import felix.rule.data.msg.*;
import felix.rule.service.actors.ActorSystemContext;
import felix.rule.web.dto.MsgDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CountDownLatch;

@Slf4j
@RestController
@RequestMapping("/api")
public class RuleController {

    @Autowired
    protected ActorSystemContext actorSystem;

    private ObjectMapper mapper = new ObjectMapper();

    @RequestMapping(value = "/rule/start", method = RequestMethod.POST)
    @ResponseBody
    public Object ruleStart(@RequestBody MsgDTO dto) throws Exception {
        try {
            CountDownLatch cdl = new CountDownLatch(1);
            final String[] result = {""};
            EngineMsgCallback tMsgCallback = new EngineMsgCallback() {
                @Override
                public void onSuccess() {
                    result[0] = "success";
                    cdl.countDown();
                }

                @Override
                public void onFailure(RuleEngineException e) {
                    result[0] = e.getMessage();
                    cdl.countDown();
                }
            };
            EngineMsg msg = EngineMsg.newMsg(dto.getType(), dto.getOriginator(), new EngineMsgMetaData(dto.getMetaData()), mapper.writeValueAsString(dto.getData()), tMsgCallback);
            QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(dto.getRuleId(), msg, null, null);
            actorSystem.tell(qMsg);
            cdl.await();
            return result[0];
        } catch (Exception e) {
            log.error("Error [{}]", e.getMessage(), e);
            throw e;
        }
    }
}
